﻿using Microsoft.VisualBasic;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Taskbar;
using System;
using System.Text;
using System.Windows.Forms;

namespace Read_the_Reader
{
    public partial class Mainform : Form
    {

        NotifyIcon TNAIcon = new NotifyIcon();

        int UnreadItems;

        WebBrowser AuxCounter = new WebBrowser();

        public Mainform()
        {
            InitializeComponent();
        }

        protected override void WndProc(ref Message message)
        {
            // Check whether a command line argument was sent via another
            // attempted instance of the application.
            if (message.Msg == NativeMethods.Info)
            {
                MessageBox.Show(Strings.Info);
                return;
            }
            if (message.Msg == NativeMethods.UpdateNow)
            {
                ReloadView();
                return;
            }
            if (message.Msg == NativeMethods.UpdateInterval)
            {
                TimerIntervalDialog();
                return;
            }

            base.WndProc(ref message);
        }

        private void ReloadBrowser_Tick(object sender, EventArgs e)
        {
            ReloadView();
        }

        private void ReloadView()
        {
            if (TaskbarManager.IsPlatformSupported)
                TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Indeterminate);
            View.Navigate("http://www.google.com/reader/i");
        }

        private void Mainform_Load(object sender, EventArgs e)
        {
            this.Text = Strings.Title;
            if (!Properties.Settings.Default.HasSeenHint)
            {
                MessageBox.Show(Strings.Hint);
                Properties.Settings.Default.HasSeenHint = true;
                Properties.Settings.Default.Save();
            }
            SetTimerInterval();
        }

        private void CountUnreadItems()
        {
            if (this.WindowState != FormWindowState.Minimized)
            {
                HtmlDocument Page = View.Document;
                if (Page != null)
                {
                    UnreadItems = 0;
                    foreach (HtmlElement Element in Page.GetElementsByTagName("span"))
                        if (Element.GetAttribute("classname") == "item-title-collapsed")
                            if (Element.OffsetRectangle.Height == 18)
                                UnreadItems++;
                    DisplayUnreadItems();
                }
            }
            else
            {
                if (TaskbarManager.IsPlatformSupported)
                    TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Indeterminate);
                AuxCounter.ScriptErrorsSuppressed = true;
                AuxCounter.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(Countalternative);
                AuxCounter.Navigate("http://www.google.com/reader/m");
            }
        }

        private void Countalternative(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (TaskbarManager.IsPlatformSupported)
                TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress);
            HtmlDocument Page = ((WebBrowser)sender).Document;
            if (Page != null)
            {
                UnreadItems = 0;
                foreach (HtmlElement Element in Page.GetElementsByTagName("a"))
                    if (Element.GetAttribute("dir") == "ltr")
                        UnreadItems++;
                DisplayUnreadItems();
            }
        }

        private void DisplayUnreadItems()
        {
            if (TaskbarManager.IsPlatformSupported)
            {
                if (UnreadItems == 0)
                    TaskbarManager.Instance.SetOverlayIcon(null, "");
                else
                    TaskbarManager.Instance.SetOverlayIcon(Properties.Resources.NewItems, "Unread items");
            }
            else
            {
                if (UnreadItems == 0)
                    TNAIcon.Visible = false;
                else
                    if (!TNAIcon.Visible)
                    {
                        if (UnreadItems == 1)
                            TNAIcon.BalloonTipText = "One unread item";
                        else
                            TNAIcon.BalloonTipText = UnreadItems.ToString() + " unread items";
                        TNAIcon.Icon = NativeMethods.GetExecutableIcon();
                        TNAIcon.BalloonTipTitle = Strings.Title;
                        TNAIcon.Visible = true;
                        TNAIcon.ShowBalloonTip(10000);
                    }
            }
        }

        private void SetTimerInterval()
        {
            ReloadTimer.Interval = Properties.Settings.Default.UpdateInterval * 1000 * 60;
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            MessageBox.Show(Strings.Info);
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            TimerIntervalDialog();
        }

        private void TimerIntervalDialog()
        {
            string foo = Properties.Settings.Default.UpdateInterval.ToString();
            int bar;
            while (true)
            {
                foo = Interaction.InputBox("Time in minutes", "Update interval", foo);
                if (foo == "")
                    break;
                if (Int32.TryParse(foo, out bar))
                    if (bar > 0)
                    {
                        Properties.Settings.Default.UpdateInterval = bar;
                        Properties.Settings.Default.Save();
                        SetTimerInterval();
                        break;
                    }
            }
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            ReloadTimer.Stop();
            ReloadTimer.Start();
            if (TaskbarManager.IsPlatformSupported)
                TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress);
            CountUnreadItems();
        }

        private void ViewTimer_Tick(object sender, EventArgs e)
        {
            if (this.WindowState != FormWindowState.Minimized)
                CountUnreadItems();
        }

        private void Mainform_Shown(object sender, EventArgs e)
        {
            ReloadTimer.Start();
            if (TaskbarManager.IsPlatformSupported)
            {
                JumpList FormerMenuBar = JumpList.CreateJumpList();
                JumpListLink UpdateNow = new JumpListLink(Environment.GetCommandLineArgs()[0], "Update now");
                UpdateNow.Arguments = Strings.ParmUpdateNow;
                UpdateNow.IconReference = new IconReference(Environment.GetCommandLineArgs()[0], 0);
                JumpListLink SetUpdateInterval = new JumpListLink(Environment.GetCommandLineArgs()[0], "Set update interval");
                SetUpdateInterval.Arguments = Strings.ParmUpdateInterval;
                SetUpdateInterval.IconReference = new IconReference(Environment.GetCommandLineArgs()[0], 0);
                JumpListLink Info = new JumpListLink(Environment.GetCommandLineArgs()[0], "Program info");
                Info.Arguments = Strings.ParmInfo;
                Info.IconReference = new IconReference(Environment.GetCommandLineArgs()[0], 0);
                FormerMenuBar.AddUserTasks(new JumpListLink[] { UpdateNow, SetUpdateInterval, Info });
                FormerMenuBar.Refresh();
            }
            else
                menuStrip1.Visible = true;
        }

    }
}
